package com.zigong.app.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.utils.ListUtils;
import com.zigong.app.R;
import com.zigong.app.application.Cache;
import com.zigong.app.application.Constances;
import com.zigong.app.beans.AddrInfo;
import com.zigong.app.beans.FUsers;
import com.zigong.app.beans.GoodsBean;
import com.zigong.app.beans.GoodsBeanInfo;
import com.zigong.app.beans.ImageUr;
import com.zigong.app.beans.ResidualIntegral;
import com.zigong.app.beans.SingleResult;
import com.zigong.app.beans.UserInfoBean;
import com.zigong.app.http.AbsListNetCallback;
import com.zigong.app.http.AbsNetCallBack;
import com.zigong.app.http.AbsStringNetCallback;
import com.zigong.app.http.NetUtils;
import com.zigong.app.ui.dialog.CommodityBuyFragment;
import com.zigong.app.ui.utils.TitleUtils;
import com.zigong.app.utils.ListTypeUtils;
import com.zigong.app.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.OnClick;

public class CommodityDetailActivity extends BaseIntegralWebActivity implements CommodityBuyFragment.IBuyClick {


    protected String h5Url;
    protected String dataUrl;
    private boolean isBuying = false;

    private GoodsBean goodsBean;

    private boolean isGettingData;//是否正在获取数据

    private AddrInfo selectAddr;

    private ArrayList<AddrInfo> addrs;

    private CommodityBuyFragment buyDialog;

    public static void StartThis(Context context, String url, String json) {
        Intent intent = new Intent(context, CommodityDetailActivity.class);
        intent.putExtra(EX_URL, url);
        intent.putExtra(EX_JSON, json);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this).useAndSetTxTitle(R.string.commodity_detail);
        Intent intent = getIntent();
        if (intent != null) {
            h5Url = intent.getStringExtra(EX_URL);
            dataUrl = intent.getStringExtra(EX_JSON);
            if (!(h5Url.contains("http://") || h5Url.contains("https://"))) {
                h5Url = "http://kscgc.sctv.com" + h5Url;
            }
            if (!(dataUrl.contains("http://") || dataUrl.contains("https://"))) {
                dataUrl = "http://kscgc.sctv.com" + dataUrl;
            }
        }
        JLog.e("detail----", "h5Url=" + h5Url + "    dataUrl=" + dataUrl);
        if (!TextUtils.isEmpty(h5Url)) {
            loadUrl(h5Url + "?gjson=" + dataUrl);
            getDetailData(dataUrl);
        } else {
//            loadUrl(Constances.URL_COMMODITY_DETAIL + "?gjson=" + h5Url);
//            if ("mockjson/goods_mock.json".equals(h5Url)) {//mockjson/goods_mock.json为初始的测试数据，
//                goodsBean = creatTestingGoods();
//            } else {
//                getDetailData(dataUrl);
//            }
        }
        getAddressInfos();
    }

    @Override
    protected void initInject() {
        initButterknifeBiner(R.layout.activity_commodity_detail);
    }

    @Override
    protected int getWevViewId() {
        return R.id.commodity_detail_web;
    }

    @OnClick(value = R.id.commodity_detail_redeem)
    public void btnClick(View v) {
        if (goodsBean == null) {
            if (isGettingData) {
                toast(R.string.data_getting_wait);
            } else {
                toast(R.string.data_wrong);
            }
        } else {
            showOrderDialog();
        }
    }

    @Override
    public void onBuyClick(int num) {
        if (selectAddr == null) {
            toast("请选择收货地址!");
            return;
        }
        if (isBuying) {
            return;
        }
        //Todo 兑换商品操作，可能会有其他的判断
        buyProduct(selectAddr.getAddrId(), num, goodsBean.getGoodsId());
    }

    @Override
    public void onAddressClick() {
        Intent intent = new Intent(this, AddressSelectActivity.class);
        intent.putExtra(EX_DATA, addrs);
        startActivityForResult(intent, 999);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999) {
            if (data != null) {
                selectAddr = (AddrInfo) data.getSerializableExtra(EX_DATA);

                if (selectAddr != null) {
                    refreshAddress();
                    boolean isAdd = false;
                    for (AddrInfo addrInfo : addrs) {
                        if (addrInfo.getAddrId().equals(selectAddr.getAddrId())) {
                            addrInfo.setStatus(1);
                            isAdd = true;
                        } else {
                            addrInfo.setStatus(0);
                        }
                    }
                    if (!isAdd) {
                        addrs.add(0, selectAddr);
                    }
                }

            }
        }
    }

    private synchronized void buyProduct(String addrId, int count, String goodsId) {
        if (!UserManager.isLoginS()) {
            toLogin();
            return;
        }
        isBuying = true;
        FUsers users = UserManager.getInstance().getUser();
        HashMap<String, Object> param = new HashMap<>();
        param.put("addrId", addrId);
        param.put("count", count);
        param.put("goodsId", goodsBean.getGoodsId());
        param.put("userId", users.getPhoneNumber());
        param.put("token", users.getToken());
        NetUtils.getNetAdapter().addGoodsOrder(getOwnerName(), param, new AbsNetCallBack<ResidualIntegral>(ResidualIntegral.class) {
            @Override
            public void onSuc(ResidualIntegral singleResult) {
                toast("兑换成功,剩余积分:" + singleResult.getIntegral());
                if (null != Cache.getInstance().getUserInfo()) {
                    Cache.getInstance().getUserInfo().setIntegral(singleResult.getIntegral());
                    CommodityDetailActivity.this.startActivity(new Intent(CommodityDetailActivity.this, CommodityExchangeSuccessActivity.class));
                    finish();
                } else {
                    initUserData();
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                JLog.e(errorMsg);
                toast(errorMsg);
                isBuying = false;
            }

            @Override
            public void onEnd() {
                super.onEnd();
            }
        });

    }

    private synchronized void getDetailData(String url) {

        if (isGettingData) {
            return;
        }
        isGettingData = true;
        NetUtils.getNetAdapter().getMallStringData(getOwnerName(), url, new AbsNetCallBack<GoodsBeanInfo>(GoodsBeanInfo.class) {


            @Override
            public void onSuc(GoodsBeanInfo goodsBeanInfo) {
                goodsBean = goodsBeanInfo.getData();
            }

            @Override
            public void onEnd() {
                super.onEnd();
                isGettingData = false;
            }

            @Override
            public void onError(Throwable ex, String errorMsg, int netCode) {
                super.onError(ex, errorMsg, netCode);
            }

            @Override
            public boolean whenLoginExpiredBackGround() {
                return true;
            }
        });
    }

    private void getAddressInfos() {
        FUsers fu = UserManager.getInstance().getUser();
        NetUtils.getNetAdapter().getAddrList(getOwnerName(), fu.getPhoneNumber(), fu.getToken()
                , new AbsListNetCallback<AddrInfo>(ListTypeUtils.AddrInfo()) {
                    @Override
                    public void onSuc(List<AddrInfo> addrInfos) {
                        addrs = new ArrayList<>();
                        addrs.addAll(addrInfos);
//                        addrs = addrInfos;
                    }

                    @Override
                    public List<AddrInfo> doInBackground(List<AddrInfo> addrInfos) {
                        if (ListUtils.isListValued(addrInfos)) {
                            for (int i = 0; i < addrInfos.size(); i++) {
                                AddrInfo ai = addrInfos.get(i);
                                if (ai.getStatus() == 1) {
                                    selectAddr = ai;
                                }
                            }
                        }
                        return super.doInBackground(addrInfos);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        refreshAddress();
                    }

                    @Override
                    public boolean whenLoginExpiredBackGround() {
                        return true;
                    }
                });
    }

    /**
     * 请求用户相关数据，积分等
     */
    private void initUserData() {
        if (UserManager.getInstance().getUser() != null) {
            //TODO 查询用户积分数据
            ArrayMap<String, Object> p = new ArrayMap<>();
            p.put("userId", UserManager.getInstance().getUser().getPhoneNumber());
            p.put("token", UserManager.getInstance().getUser().getToken());
            NetUtils.getNetAdapter().postGetUserData(getOwnerName(), p, new AbsNetCallBack<UserInfoBean>(UserInfoBean.class) {
                @Override
                public void onSuc(UserInfoBean userInfoBean) {
                    Cache.getInstance().setUserInfo(userInfoBean);
                }

                @Override
                public void onEnd() {
                    super.onEnd();
                    finish();
                }

                @Override
                public void onError(Throwable ex, String errorMsg) {
                    super.onError(ex, errorMsg);
                }


            });
        } else {
            toLogin();
        }
    }

    private void showOrderDialog() {
        String icon = null;
        if (ListUtils.isListValued(goodsBean.getGoodsIcon())) {
            String iu = goodsBean.getGoodsIcon().get(0);
            if (iu != null && !TextUtils.isEmpty(iu)) {
                icon = iu;
            }
        }
        if (buyDialog != null) {
            try {
                buyDialog.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        buyDialog = CommodityBuyFragment.newInstance(parseToFloat(goodsBean.getGoodsPrice(), 0)
                , parseToInteger(goodsBean.getGoodsIntegral(), 0), icon, selectAddr == null ? "" : selectAddr.getAddress());
        buyDialog.setBuyClick(this);
        safeShowDialog(buyDialog, "commodityBuy");

    }

    /**
     * 刷新显示的收货地址
     */
    private void refreshAddress() {
        if (buyDialog != null) {
            buyDialog.setAddress(selectAddr != null ? selectAddr.getAddress() : null);
        }
    }

    private float parseToFloat(String str, int def) {
        if (!TextUtils.isEmpty(str)) {
            if (str.matches("\\d+") || str.matches("\\d+.\\d+")) {
                return Float.parseFloat(str);
            }
        }
        return def;
    }

    private int parseToInteger(String str, int def) {
        if (!TextUtils.isEmpty(str) && str.matches("\\d+")) {
            return Integer.parseInt(str);
        }
        return def;
    }

    private GoodsBean creatTestingGoods() {
        GoodsBean gb = new GoodsBean();
        gb.setGoodsIntegral(((int) (Math.random() * 501)) + "");
        gb.setGoodsPrice(Math.random() * 20 + "");
        return gb;
    }


}
